package com.android.flowoflife.hardware;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.android.flowoflife.IFlowOfLifeConstants;

import android.content.Context;
import android.os.Environment;

public class StorageAccess {
	static class StorageAccessException extends IOException {
		private static final long serialVersionUID = 6462832268077730289L;

		public StorageAccessException(String message) {
			super("Environment external storage state: " + message);
		}
	}
	
	private Context context;
	
	public StorageAccess(Context context) {
		this.context = context;
	}
	
	public void writeIntoInternalMemory(int frame, byte[] data) throws IOException {				
		write(data, context.openFileOutput(frame + "." + IFlowOfLifeConstants.IMAGE_FILE_EXTENSION, Context.MODE_WORLD_READABLE));
	}
	
	public void writeIntoExternalMemory(int frame, byte[] data) throws IOException {
		String externalStorageState = Environment.getExternalStorageState();
		if (!Environment.MEDIA_MOUNTED.equalsIgnoreCase(externalStorageState))
			throw new StorageAccessException(externalStorageState);
		
		File root = Environment.getExternalStorageDirectory();
		if (!root.canWrite())
			throw new StorageAccessException(Environment.getExternalStorageState());
		
		File appDirectory = new File(root, "flowOfLife");
		if (!appDirectory.exists()) {
			if(!appDirectory.mkdir())
				throw new StorageAccessException(Environment.getExternalStorageState());
		}
		
		File file = new File(appDirectory, frame + "." + IFlowOfLifeConstants.IMAGE_FILE_EXTENSION);
		
		write(data, new FileOutputStream(file));
	}
	
	private void write(byte[] data, FileOutputStream outputStream) throws IOException {
		outputStream.write(data);
		outputStream.flush();
		outputStream.close();
	}
	
	public InputStream readFromExternalMemory(int frame) throws IOException {
		String externalStorageState = Environment.getExternalStorageState();
		if (!(Environment.MEDIA_MOUNTED.equalsIgnoreCase(externalStorageState) || Environment.MEDIA_MOUNTED_READ_ONLY.equalsIgnoreCase(externalStorageState)))
			throw new StorageAccessException(externalStorageState);
		
		File root = Environment.getExternalStorageDirectory();		
		File appDirectory = new File(root, "flowOfLife");
		File file = new File(appDirectory, frame + "." + IFlowOfLifeConstants.IMAGE_FILE_EXTENSION);
		return new FileInputStream(file);
	}
	
	public InputStream readFromInternalMemory(int frame) throws IOException {
		return context.openFileInput(frame + "." + IFlowOfLifeConstants.IMAGE_FILE_EXTENSION);
	}
}
